<template>
  <div class="flow-table" @mousemove="handleMouseMove" @mouseleave="handleMouseLeave"
    :style="{ height: currentFlowTableHeight + 'px' }">
    <transition-group name="fade" tag="div">
      <div class="flow-row" v-for="(news) in currentPageNews" :key="news.id">
        <div :class="{ 'flow-itemNews': news.pic == 'news', 'flow-itemTip': news.pic == 'tips' }">
          <div class="news-icon">
            <img :src="getNewsIcon(news.pic)" alt="news-icon" />
          </div>
          <div class="news-time">{{ news.newtime }}</div>
          <div class="news-content">{{ news.title }}</div>
        </div>
      </div>
    </transition-group>

    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">&lt;</button>
      <span>{{ currentPage }} / {{ totalPages }}</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">&gt;</button>
    </div>
  </div>
</template>

<script>


function formatTimeString(date) {
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
} //生成 hh-mm类的时间

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 7,
      news: [],
      scrollIntervalId: null,
      fetchIntervalId: null,
      isMouseInside: false,
      lastMouseMoveTime: null,
      mouseInactiveTimeout: 5000, // 鼠标不活动超过10秒后开始自动滚动
      fetchInterval: 10000, // 5秒钟刷新一次数据
      currentFlowTableHeight: 700, // 设置初始高度为 300px
      normalFlowTableHeight: 700, // 设置正常高度为 300px
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.news.length / this.pageSize);
    },
    currentPageNews() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.sortedNews.slice(startIndex, endIndex);
    },
    sortedNews() {
      const sorted = this.news.slice().sort((a, b) => new Date(b.time) - new Date(a.time)); //根据接受到新闻的时间排序，而非新闻标题的时间排序

      return sorted;
    }
  },
  methods: {
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.setFlowTableHeight(0); // 将高度设置为 0
        setTimeout(() => {
          this.setFlowTableHeight(this.normalFlowTableHeight); // 在 500ms 后将高度恢复到正常值
        }, 1500);
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.setFlowTableHeight(0); // 将高度设置为 0
        setTimeout(() => {
          this.setFlowTableHeight(this.normalFlowTableHeight); // 在 500ms 后将高度恢复到正常值
        }, 1500);
      }
    },
    setFlowTableHeight(height) {
      this.currentFlowTableHeight = height;
    },
    autoFetchStocks() {
      // this.fetchIntervalId = setInterval(() => {
      //   if (!this.isMouseInside || (new Date().getTime() - this.lastMouseMoveTime > this.mouseInactiveTimeout)) {
      //     this.news = this.fetchNews();
      //   }
      // }, this.fetchInterval);
    },
    stopAutoFetchStocks() {
      clearInterval(this.fetchIntervalId);
      this.fetchIntervalId = null;
    },
    handleMouseMove() {
      this.isMouseInside = true;
      this.updateLastMouseMoveTime();
    },
    handleMouseLeave() {
      this.isMouseInside = false;
      this.updateLastMouseMoveTime();
    },
    updateLastMouseMoveTime() {
      this.lastMouseMoveTime = new Date().getTime();
    },
    autoScroll() {
      this.scrollIntervalId = setInterval(() => {
        if (!this.isMouseInside || new Date().getTime() - this.lastMouseMoveTime > this.mouseInactiveTimeout) {
          this.nextPage();
        }
      }, 5000);
    },
    stopAutoScroll() {
      clearInterval(this.scrollIntervalId);
      this.scrollIntervalId = null;
    },
    //   fetchNews() {
    //     axios.get('/news/findAll').then((response) => {
    //       console.log(response.data);
    //       this.news = response.data.data;
    //     }).catch((error) => {
    //   console.error('Error', error);
    // });
    //   },
    fetchNews() {
      fetch('/news/findAll')
        .then(response => response.json())
        .then(data => {
          console.log('Fetched data:', data); // 打印 data 内容
          if (data.code === 6000 && Array.isArray(data.data)) {
            this.news = data.data.map(item => {
              item.newtime = formatTimeString(new Date(item.time));
              return item;
            });
          } else {
            console.error('Unexpected response format:', data);
          }
        })
        .catch(error => {
          console.error('Error fetching news:', error);
        });
    },
    setupWebSocket() {
      this.ws = new WebSocket('ws://localhost:8080/news'); // WebSocket服务器URL

      this.ws.onopen = () => {
        console.log('WebSocket连接已建立');
      };

      this.ws.onmessage = (event) => {
        const newNewsItem = JSON.parse(event.data);
        newNewsItem.newtime = formatTimeString(new Date(newNewsItem.time));
        this.news.push(newNewsItem); // 将新新闻项添加到news数组
      };

      this.ws.onclose = () => {
        console.log('WebSocket连接已关闭');
      };

      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
      };
    },
    getNewsIcon(type) {
      return type === 'tips' ? require('../assets/bell.svg') : require('../assets/news.svg');
    }
  },
  mounted() {
    this.fetchNews();
    this.autoScroll();
  },
  beforeUnmount() {
    this.stopAutoScroll();
    this.stopAutoFetchStocks();
  },
};
</script>

<style scoped>
/* 保留原有的 CSS 样式并添加新的样式 */
.flow-table {
  color: #f0f0f0;
  font-size: 14px;
  width: 92%;
  height: 100%;
  margin: 0 auto;
  /* height: 605px; 
  /* 很重要的高度 */
  overflow: hidden;
}

.flow-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
  height: 100%;
}

.flow-itemTip {
  width: 100%;
  display: flex;
  padding: 22px;
  justify-content: space-between;
  border: solid 1px #e70a0a;
  box-shadow: inset 0 0 30px 6px rgba(231, 10, 10, 0.5);
  align-items: center;
  /* Vertically center the icon */
}

.flow-itemNews {
  width: 100%;
  display: flex;
  padding: 22px;
  justify-content: space-between;
  border: solid 1px #faf7f7;
  box-shadow: inset 0 0 30px 6px rgba(104, 99, 99, 0.5);
  align-items: center;
  /* Vertically center the icon */
}

.news-icon {
  width: 24px;
  height: 24px;
  margin-top: 8px;
}

.news-content {
  flex-grow: 1;
  color: #f8f6f6f3;
  margin-right: 10px;
}

.news-time {
  color: #add8e6;
  margin-left: 8px;
  align-items: center;
  /* Vertically center the icon */
}

.pagination {
  position: absolute;
  bottom: 1px;
  left: 38%;
  display: flex;
  justify-content: center;
  margin-bottom: 12px;
}

.pagination button {
  background-color: #3f88e7;
  color: #f0f0f0;
  border: none;
  padding: 4px 8px;
  cursor: pointer;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination span {
  margin: 0 12px;
}


/* 过渡效果定义 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 1.5s;
}

.fade-enter,
.fade-leave-to

/* .fade-leave-active in <2.1.8 */
  {
  opacity: 0;
}

.move-transition {
  transition: all 1.5s ease;
}
</style>